import configparser
import utils
import time

headers = {
    "X-Requested-With": "XMLHttpRequest"
}


# 一键登录
class Lighthouse:
    def __init__(self, config_file):
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self.config.read(config_file, encoding='utf-8')
        self.data = {}
        self.session = utils.requests_retry_session()
        self.ensure('Url', '网址', 'http://account.w6t8d.com/admin')
        self.ensure('User', '用户')
        self.ensure('Password', '密码')

    def ensure(self, key, prompt, example=None):
        self.data[key] = self.config.get('Login', key, fallback=None)
        if self.data[key] is None:
            self.data[key] = input("请输入灯塔系统{}：".format(prompt) if example is None else "请输入灯塔系统{}（如{}）："
                                   .format(prompt, example))
        else:
            print("使用保存的登录系统{}: {}".format(
                prompt, '****' if key == 'Password' else self.data[key]))

    def get_url(self):
        return self.data['Url']

    def get_username(self):
        return self.data['User']

    def get_password(self):
        return self.data['Password']

    def resume_session(self):
        try:
            test = self.session.post(self.get_url() + '/index/login?is_qrlogin=0',
                                     data={
                                         "username": self.get_username(),
                                         "password": self.get_password()}, headers=headers, verify=False)
            if test.status_code == 200:
                json_response = test.json()
                if json_response['code'] == 1:
                    return json_response['code']
                else:
                    return False
            else:
                return False
        except ValueError:
            return False

    def get_wx_cookie(self, gh_id):
        data = {"filter": "{\"ghid\": \"%s\"}" %(gh_id), '_': int(time.time() * 1000)}
        resp_sign = self.session.get(
            "http://account.w6t8d.com/admin/wechataccount/account/index?sort=id&order=desc&offset=0&limit=10",
            headers=headers, params=dict(data), verify=False)
        json_sign = resp_sign.json()
        resp = self.session.post('{}/onekeyload/Onekeyload/getcookie'.format(self.get_url()),
                                 data={
                                     "ghid": gh_id,
                                     "sign": json_sign['rows'][0]['sign'],
                                     "signtime": json_sign['rows'][0]['signtime']}, headers=headers, verify=False)
        try:
            json_resp = resp.json()
            if json_resp['code'] == 0:
                return json_resp['cookie']
            else:
                print('{} 一键登录状态异常: {}'.format(gh_id, json_resp['code']))
                return None
        except ValueError:
            print('获取Cookie错误')
            print(resp.content)
            return None


def use_default_login():
    srv = Lighthouse('config.ini')
    if srv.resume_session():
        print('回话有效，可进行下一步')
    else:
        print('回话失效，重新登录')
    return srv


if __name__ == '__main__':
    use_default_login()
